package spec.chenli;

import org.omg.CORBA.Request;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

//@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
                request.setCharacterEncoding("utf-8");
                response.setCharacterEncoding("utf-8");
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
            // 1、获取浏览器端输入的用户名和密码
            String bUsername = request.getParameter("username");
            String bPassword = request.getParameter("password");
            // 2、从数据库取用户输入的用户名记录
            //      注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //      建立连接
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/1613580007", "root", "123456789");
            //      创建查询语句
            Statement s = con.createStatement();
            ResultSet rs = s.executeQuery("select * from user where username='" + bUsername+" '");
            //  3、判断结果集是否有没有内容
            if(!rs.next()){
                out.println("<h1>登录失败，系统里找不到该用户名，请核实后重新登录</h1><br>");
            }else{
                String dbPassword = rs.getString("password");
                if(dbPassword.equals(bPassword)){
                    out.println("<h1>登录成功</h1>");
                   // out.println("<a href=\"http://localhost:8080/NewsAdd.html\">点击跳转</a>");
                    response.sendRedirect("listnew");

                }else{
                    out.println("<h1>登录失败，密码错误，请想想再重新登录</h1><br>");
                    out.print("<a href=\"http://localhost:8080/Login.html\">重新登录</a>");
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//          //response.setContentType("text/html");
//         // PrintWriter pr=response.getWriter();
//         // pr.print("<h1>"+"Hello Servlet"+"<h1>");
        //设置响应内容类型
        response.setContentType("text/html");
        //设置逻辑实现
        PrintWriter out = response.getWriter();
        out.println("<h1>登录成功</h1>");
    }
}

